<template>
    <div class="qilin-treePerson flex-column">
        <div class="qilin-treePerson-selected qilin-p-4 flex-column">
            <div class="qilin-treePerson-selected-text qilin-mb-2">已选择：</div>
            <div class="qilin-treePerson-selected-list flex-row beauty-scrollbar-y">
                <div class="qilin-treePerson-selected-list-item qilin-bg-primary qilin-px-4 qilin-mr-6 qilin-mb-3 qilin-radius-default"
                    v-for="item in selectedData"
                >
                    <span>{{ item.deptName + " - " + item.nickName }}</span>
                    <span class="qilin-ml-2 qilin-text-medium" @click="deleteSelectedData(item)">×</span>
                </div>
            </div>
        </div>
        <div class="qilin-treePerson-content flex-row">
            <QilinTree v-model:treeConfig="treeConfig"></QilinTree>
            <div class="qilin-treePerson-content-table flex-column qilin-p-6">
                <div class="qilin-treePerson-content-table-header flex-row qilin-mb-6">
                    <div class="qilin-treePerson-content-table-header-title">
                        {{deptInfo.label+" "+deptInfo.count}}人
                    </div>
                    <div class="qilin-treePerson-content-table-header-search">
                        <el-input placeholder="请输入" v-model="searchContent" name="input">
                            <template #append>
                                <el-button icon="Search" @click="searchData"></el-button>
                            </template>
                        </el-input>
                    </div>
                </div>
                <QilinTable ref="tableConfigRef" v-model:tableConfig="tableConfig"
                    @selectRowData="selectRowData" @selectAllRowData="selectAllRowData"
                ></QilinTable>
            </div>
        </div>
    </div>
</template>

<script setup>
/**
 * 组件介绍：选择部门人员组件封装
 * 功能描述：支持多选、人员姓名搜索、快速删除、显示对应选中人员的部门名称、编辑回显
 * 
 * @author Qilin
 * @CreateDate 2025-01-20 创建日期
 * @lastUpdatePerson Qilin 最后修改人
 * @lastUpdateDate 2025-05-28 最后修改日期
 */
import { getMenuListData,getTableListData } from "@/api/index.js";

/*
    响应式选项区域
*/
const propsValue = defineProps({
    isCheckRefresh:{ //是否选择人员时就更新选中数据
        type:Boolean,
        default:false
    }
});
// 暴露父组件自定义方法
const emits=defineEmits(["success"]);


/*
    数据变量定义区域
*/
// 选择节点信息
let deptInfo=reactive({
    label:"",
    count:0,
    deptId:""
});
// 查询输入内容
let searchContent=ref("");
// 获取表格元素DOM
const tableConfigRef=ref(null);
let selectedData = ref([]); //已选择的数据


/*
    计算属性等代码区域
*/


/*
    逻辑脚本代码区域
*/
// 初始化加载
const initRenderData=(data)=>{
    // console.log(data);
    selectedData.value = [...data] || [];
    renderSelectedTable(selectedData.value);
};
// 回显表格选中事件监听
const renderSelectedTable=(data)=>{
    // console.log(data,"------")
    // 先清空全选
    tableConfigRef.value.clearSelection();
    // 再渲染已选
    nextTick(()=>{
        data.forEach((item1)=>{
            const targetRow = tableConfig.tableData.find(item2 => item2.userId === item1.userId);
            if(targetRow) tableConfigRef.value.toggleRowSelection(targetRow,true); //选中已选数据
        });
    });
};
// 删除选中数据事件监听
const deleteSelectedData=(obj)=>{
    nextTick(()=>{
        selectedData.value = selectedData.value.filter(item => item.userId !== obj.userId);
        const targetRow = tableConfig.tableData.find(item2 => item2.userId === obj.userId);
        if(targetRow) tableConfigRef.value.toggleRowSelection(targetRow,false); //取消选中已选数据
    });
};
// 选择树节点事件监听
const nodeClick=(item,node,treeNode,e)=>{
    // console.log(item);
    searchContent.value = "";
    deptInfo.label=item.label;
    deptInfo.id=item.id;
    getTableData(item.id);
};
// 点击查询按钮事件监听
const searchData=()=>{
    deptInfo.label="查询结果";
    getTableData(null,searchContent.value);
};
// 获取通讯录人员数据事件监听
const getMenuListDataInfo=()=>{
    getMenuListData().then((res)=>{
        if(res.code === 200){
            // console.log(res)
            treeConfig.data=res.data;
            treeConfig.itemConfig.defaultExpandedKeys=[res.data[0].id];
            deptInfo.label=res.data[0].label;
            getTableData(res.data[0].id);
        }else{
            ElMessage({
                message:res.msg || "系统错误",
                type:"error"
            });
        };
    });
};
// 选中某行数据事件监听
const selectRowData=(selection,row)=>{
    // console.log(selection,row);
    if(!selectedData.value.some((item)=>{return item.userId === row.userId})){
        selectedData.value.push(row);
    }else{ //取消选中
        selectedData.value = selectedData.value.filter((item)=>{
            return item.userId !== row.userId;
        });
    }
    if(propsValue.isCheckRefresh) emits("success",selectedData.value);
};
// 选中全选数据事件监听
const selectAllRowData=(selection)=>{
    // console.log(selection.length,tableConfig.tableData,selectedData.value);
    if(selection.length === 0){ //取消全选时
        selectedData.value = selectedData.value.filter((item1)=>{
            return !tableConfig.tableData.some((item2)=>{
                return item1.userId === item2.userId;
            });
        });
    }else{
        selection.forEach((item1)=>{
            const someRow = selectedData.value.some(item2=> item2.userId === item1.userId);
            if(!someRow) selectedData.value.push(item1);
        });
    }
    if(propsValue.isCheckRefresh) emits("success",selectedData.value);
};
// 初始化获取表格数据
const getTableData=(id,name)=>{
    let params={
        pageNum:1,
        pageSize:999
    };
    if(id){
        params.deptId=id;
    }else{
        params.nickName=name;
    };
    getTableListData(params).then((res)=>{
        if(res.code === 200){
            // console.log(res.rows);
            tableConfig.tableData=res.rows;
            tableConfig.paginationsObj.total=deptInfo.count=res.total;
            renderSelectedTable(selectedData.value);
        }else{
            ElMessage({
                message:res.msg || "系统错误",
                type:"error"
            });
        };
    });
};
// 确认选择可见范围事件监听
const confirmSelected=()=>{
    // console.log(selectedData.value);
    emits("success",selectedData.value);
};

// 树组件配置项
const treeConfig=reactive({
    itemConfig:{
        showCheckbox:false,
        checkOnClickNode:true,
        highlightCurrent:true,
        nodeKey:"id",
        defaultCheckedKeys:[],
        defaultExpandedKeys:[],
        defaultExpandAll:false,
        nodeClick:nodeClick
    },
    props:{
        label:"label",
        children:"children"
    },
    data:[]
});
// 表格组件配置项
const tableConfig=reactive({
    elTableConfig:{
        border:true,
        rowKey:"userId"
    },
    headerConfig:[
        {
            type:"checkbox",
            width:60
        },
        {
            type:"sortIndex",
            align:"center",
            width:60
        },
        {
            label:"姓名",
            prop:"nickName",
            type:"text",
            align:"center"
        },
        {
            label:"部门",
            prop:"deptName",
            type:"text",
            align:"center"
        }
    ],
    tableData:[],
    paginationsObj:{
        isHide:true,
        currentPage:1, //当前页
        pageSize:10, //当前每页数量
        pageSizes:[10,20,30], //每页显示多少条选项集
        total:0, //表格总数量
        layout:"total,sizes,prev,pager,next,jumper"
    }
});


/*
    生命周期等代码区域
*/
getMenuListDataInfo();

defineExpose({
    initRenderData,
    confirmSelected
});

</script>

<style lang="scss" scoped>
.qilin-treePerson{
    width:100%;
    height:4.5rem;
    border:1px solid var(--qilin-border-color);
    >.qilin-treePerson-selected{
        height:1.2rem;
        border:1px dashed var(--qilin-border-color);
        >.qilin-treePerson-selected-list{
            flex:1;
            min-height:0;
            flex-wrap: wrap;
            align-items:baseline;
            >.qilin-treePerson-selected-list-item{
                height:auto;
                cursor:pointer;
            }
        }
    }
    >.qilin-treePerson-content{
        flex:1;
        min-height:0;
        >.QilinTree{
            flex:1;
            min-width:2rem;
        }
        >.qilin-treePerson-content-table{
            flex:3;
            border-left:1px solid var(--qilin-border-color);
            >.qilin-treePerson-content-table-header{
                justify-content:space-between;
                align-items:center;
                >.qilin-treePerson-content-table-header-title{
                    color:var(--qilin-color-info);
                }
                :deep(>.qilin-treePerson-content-table-header-search){
                    .el-input__wrapper{
                        border-radius: 999px 0 0 999px;
                        box-shadow:none !important;
                        border:1px solid #dcdfc6;
                    }
                    .el-input-group__append{
                        border-radius: 0 999px 999px 0;
                    }
                }
            }
        }
    }
}
</style>
